package com.cloudkinto.service.stock.impl;

import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.common.BeanConvert;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.utils.ExcelUtils;
import com.cloudkinto.common.utils.TimeUtils;
import com.cloudkinto.common.utils.ali.AliOss;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dao.*;
import com.cloudkinto.entity.*;
import com.cloudkinto.service.company.CompanyService;
import com.cloudkinto.service.finance.vo.IdAndNameEntity;
import com.cloudkinto.service.shop.ShopService;
import com.cloudkinto.service.stock.StockLogService;
import com.cloudkinto.service.stock.vo.StockSnapshotExportVo;
import com.cloudkinto.service.stock.vo.log.StockLogExportVo;
import com.cloudkinto.service.stock.vo.log.StockLogPageRes;
import com.cloudkinto.service.storage.StorageService;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author 张永远
 * @since 2020-06-10
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class StockLogServiceImpl extends ServiceImpl<StockLogDao, StockLogDo> implements StockLogService {
    @Autowired
    private StockLogDao dao;
    @Autowired
    private ShopDao shopDao;
    @Autowired
    private StorageDao storageDao;
    @Autowired
    private StorageService storageService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private ShopService shopService;
    @Autowired
    private ProductInfoDao productDao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private CompanyService companySerVice;
    @Value("${gbc.uploadPath.fileUrl}")
    private String fileUrl;

    @Value("${gbc.uploadPath.filePathTemp}")
    private String filePathTemp;


    @Override
    public SingleResult pageInit(Long companyId, Long userId) {
        Map map = new HashMap();
        map.put("storageList", storageService.getStorageList());

//        List<IdAndNameEntity> type = new ArrayList<>();
//        type.add(new IdAndNameEntity(0, "仓库盘点"));
//        type.add(new IdAndNameEntity(1, "出库"));
//        type.add(new IdAndNameEntity(2, "入库"));
        List<Map> shopList = companySerVice.getInitList(companyId);
        map.put("shopList", shopList);
        List<Map> shopTree = shopService.selectShopListInit(userId, companyId);
        map.put("shopTree", shopTree);
//        map.put("type", type);
        return SingleResult.success(map);
    }

    @Override
    public PageResult getListPage(Map<String, String> map) {
        QueryWrapper<StockLogDo> wrapper = queryBuild(map);
        IPage<StockLogDo> page = pageInit(map);
        page = this.page(page, wrapper);
        List<StockLogPageRes> resList = handlerListAfter(page.getRecords());
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }

    public boolean saveAutoSendOutLog(Integer status, Long productId, Long shopId, Long storageId, int count, Integer afterCount, Long companyId, Long userId, String orderNo) {
        return this.saveAutoSendOutLog(status, productId, shopId, storageId, count, afterCount, companyId, userId, orderNo,null);
    }
    /**
     * 不良品的库存日志
     *
     * @param status     0 良品 1不良品
     * @param productId  产品Id
     * @param shopId     所属店铺
     * @param storageId  所属仓库
     * @param count      变动数量
     * @param afterCount 剩余数量
     * @param companyId  公司标识
     * @param userId     操作人
     * @param orderNo    订单号
     * @return
     */
    @Override
    public boolean saveAutoSendOutLog(Integer status, Long productId, Long shopId, Long storageId, int count, Integer afterCount, Long companyId, Long userId, String orderNo, Long flowingId) {
        StockLogDo stockLogDo = new StockLogDo();
        ProductInfoDo productInfoDo = productDao.selectById(productId);
        if (productInfoDo != null) {
            stockLogDo.setCommoditySku(productInfoDo.getCommoditySku());
        }
        stockLogDo.setShopId(shopId);
        stockLogDo.setStorageId(storageId);
        stockLogDo.setCount(count);
        if (count > 0) {
            stockLogDo.setType(2);
        } else if (count < 0) {
            stockLogDo.setType(1);
        } else {
            return true;
        }
        stockLogDo.setStatus(status);
        stockLogDo.setAfterCount(afterCount);
        stockLogDo.setCompanyId(companyId);
        stockLogDo.setProductId(productId);
        stockLogDo.setThirdOrderNumber(orderNo);
        stockLogDo.setCreateTime(new Date());
        stockLogDo.setCreateBy(userId);
        stockLogDo.setFlowingId(flowingId);
        stockLogDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
        return save(stockLogDo);
    }

    @Override
    public List<StockLogPageRes> getList(Map<String, String> map) {
        QueryWrapper<StockLogDo> wrapper = queryBuild(map);
        List<StockLogPageRes> resList = handlerListAfter(dao.selectList(wrapper));
        return resList;
    }

    /**
     * 良品的库存日志
     *
     * @param productId
     * @param shopId
     * @param storageId
     * @param count
     * @param afterCount
     * @param companyId
     * @param userId
     * @param orderNo
     * @return
     */
    @Override
    public boolean saveAutoSendOutLog(Long productId, Long shopId, Long storageId, int count, Integer afterCount, Long companyId, Long userId, String orderNo) {
        return saveAutoSendOutLog(0, productId, shopId, storageId, count, afterCount, companyId, userId, orderNo);
    }

    //查询分页列表之后对列表数据的处理
    private List<StockLogPageRes> handlerListAfter(List<StockLogDo> list) {
        List<StockLogPageRes> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            for (StockLogDo stockLogDo : list) {
                StockLogPageRes res = new StockLogPageRes();
                res.setId(stockLogDo.getId());
                res.setAfterCount(stockLogDo.getAfterCount());
                res.setCommoditySku(stockLogDo.getCommoditySku());
                ProductInfoDo productInfoDo = productDao.selectById(stockLogDo.getProductId());
                if (productInfoDo != null) {
                    res.setStorageSku(productInfoDo.getStorageSku());
                }
                res.setCount(stockLogDo.getCount());
                res.setCreateTime(stockLogDo.getCreateTime());
                ShopDo shopDo = shopDao.selectById(stockLogDo.getShopId());
                if (shopDo != null) {
                    res.setShop(shopDo.getShopName());
                }
                UserDo userDo = userDao.selectById(stockLogDo.getCreateBy());
                if (userDo != null) {
                    res.setOperateBy(userDo.getUserName());
                }
                StorageDo storageDo = storageDao.selectById(stockLogDo.getStorageId());
                if (storageDo != null) {
                    res.setStorage(storageDo.getStorageName());
                }
                CompanyDo companyDo = companyDao.selectById(stockLogDo.getCompanyId());
                if (companyDo != null) {
                    res.setCompanyCode(companyDo.getCompanyCode());
                }
                res.setThirdOrderNumber(stockLogDo.getThirdOrderNumber());
                if (stockLogDo.getType() == 0) {
                    res.setType("仓库盘点");
                } else if (stockLogDo.getType() == 1) {
                    res.setType("出库");
                } else if (stockLogDo.getType() == 2) {
                    res.setType("入库");
                }
//                if (stockLogDo.getStatus() == 0) {
//                    res.settta("良品");
//                } else if (stockLogDo.getStatus() == 1) {
//                    res.setType("不良品");
//                }
                res.setStatus(stockLogDo.getStatus());
                UserDo createBy = userDao.selectById(stockLogDo.getCreateBy());
                if (createBy != null) {
                    res.setCreateByName(createBy.getUserName());
                }

                result.add(res);
            }
        }
        return result;
    }

    private IPage<StockLogDo> pageInit(Map<String, String> map) {
        IPage<StockLogDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<StockLogDo> queryBuild(Map<String, String> map) {
        QueryWrapper<StockLogDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("keyword"))) {
            wrapper.and(i -> {
                i.like("commodity_sku", map.get("keyword"))
                        .or().like("third_order_number", map.get("keyword"));
            });
        }
        if (StringUtils.isNotBlank(map.get("shopId"))) {
            wrapper.eq("shop_id", map.get("shopId"));
        }
        if (StringUtils.isNotBlank(map.get("endDate"))) {
            wrapper.le("create_time", map.get("endDate"));
        }
        if (StringUtils.isNotBlank(map.get("startDate"))) {
            wrapper.ge("create_time", map.get("startDate"));
        }
        if (StringUtils.isNotBlank(map.get("storageId"))) {
            wrapper.eq("storage_id", map.get("storageId"));
        }
        if (StringUtils.isNotBlank(map.get("companyId"))) {
            wrapper.eq("company_id", map.get("companyId"));
        }
        if (StringUtils.isNotBlank(map.get("status"))) {
            wrapper.eq("status", map.get("status"));
        }
        if (StringUtils.isNotBlank(map.get("type"))) {
            wrapper.eq("type", map.get("type"));
        }
        return wrapper.orderByDesc("id");
    }

    @Override
    public int selectInCount(Long storageId, Long shopId, Long productInfoId, String commoditySku, int beforeDays) {
        return dao.selectInTotalCount(storageId, shopId, productInfoId, commoditySku, TimeUtils.getCurrentDateFormat(-beforeDays));
    }

    @Override
    public int selectLogCount(Long storageId, Long shopId, Long productInfoId, String commoditySku, int type, String
            startDate, String endDate) {
        return dao.selectLogTotalCount(storageId, shopId, productInfoId, commoditySku, type, startDate, endDate);
    }


    @Override
    public String exportExcel(Map<String, String> map, String fileName) {
        List<StockLogPageRes> list = getList(map);
        if (list.size() > 9999) {
            throw new BizException(SysConstant.File_Export_ToMuch, 10000);
        }
        List<StockLogExportVo> exportVoList = new ArrayList<>();
        list.forEach(et -> {
            StockLogExportVo exportVo = BeanConvert.INSTANCE.stockLogExportVo(et);
            exportVoList.add(exportVo);
        });
        ExportParams exportParams = new ExportParams();
        exportParams.setCreateHeadRows(true);
        exportParams.setHeaderColor(IndexedColors.YELLOW.getIndex());
        String objectNameTemporary = "";
        try {
            ExcelUtils.exportExcelToSave(exportVoList, StockLogExportVo.class, fileName, exportParams, filePathTemp);
            objectNameTemporary = AliOss.temporaryFile2(fileName, new File(filePathTemp + File.separator + fileName));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("导出文件失败" + e.getMessage());
        }
        return fileUrl + objectNameTemporary;
    }
}
